Bubble Sort

#C#

Posted by Phyxsius on 2023-09-24


internal class Program
{
    private static void Main(string[] args)
    {
        int[] ary = new int[5];    //宣告陣列大小為5

        Random rnd = new Random();  //產生亂數初始值

        for (int i=0; i<ary.Length; i++)
        {
            ary[i] = rnd.Next(1, 10);   //亂數產生,亂數產生的範圍是1~9
        }

        Console.WriteLine("原始陣列內容:");
        showArray(ary);

        BubbleSort(ary);

        Console.WriteLine("由小到大排序後陣列內容:");
        showArray(ary);
    }

    static void BubbleSort(int[] ary)
    {
        System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
        stopWatch.Start();  //計算程式時間開始

        int counter = 0;

        for (int i = 0; i < ary.Length; i++)
        {
            for (int j = 0; j < ary.Length; j++)
            {
                if (ary[i] < ary[j])
                {
                    swap(ary, i, j);
                }
                counter++;
            }
            Console.Write($"第{i+1}輪結果:");
            showArray(ary);
        }
        Console.WriteLine("執行次數:" + counter);

        stopWatch.Stop();   //計算程式時間結束
        Console.WriteLine("程式執行時間(秒):" + (stopWatch.Elapsed.TotalMilliseconds/1000));
    }

    //兩個值互相交換
    static void swap(int[] ary, int value1, int value2)
    {
        int tmp = ary[value2];
        ary[value2] = ary[value1];
        ary[value1] = tmp;
    }

    //顯示陣列內容
    static void showArray(int[] ary)
    {
        for (int i=0; i<ary.Length; i++)
        {
            Console.Write(ary[i] + ",");
        }
        Console.WriteLine();
    }
}

#C#







Related Posts

網頁前後端簡易架構筆記

網頁前後端簡易架構筆記

CSS 的模組化(OOCSS、SMACSS、BEM)

CSS 的模組化(OOCSS、SMACSS、BEM)

React 中 Class Component 的生命週期

React 中 Class Component 的生命週期


Comments